package com.boyi.core;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class CM implements ApplicationContextAware {
    private static ApplicationContext context;

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBeanByType(Class clazz, Type type) {
        String[] beanNamesForType = context.getBeanNamesForType(clazz);
        for (String s : beanNamesForType) {
            // 根据名字获取bean
            Object bean = context.getBean(s);
            // 取得该bean 的泛型类型
            Type type1 = bean.getClass().getGenericSuperclass();
            Class c = (Class) type1;
            Type superClass = c.getGenericSuperclass();
            //得到当前类上所有的泛型类型Class
            Type[] types = ((ParameterizedType) superClass).getActualTypeArguments();
            //得到具体传入的泛型类Class对象
            if (clazz.isAssignableFrom(bean.getClass()) && type.equals(types[0])) {
                return (T) bean;
            }
        }
        return null;
    }


    public static <T> T getBean(String name) {
        context.getBeanDefinitionNames();
        return (T) context.getBean(name);
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    public static void setContext(ApplicationContext context) {
        CM.context = context;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
